import pandas as pd
from sklearn.preprocessing import LabelEncoder

data_flf=pd.read_csv('Housing.csv')
# print("总数居:",data.count())

# data_na=data_flf.isnull().sum(axis=0);
# print(data_na)

data_flf=data_flf.dropna()
print("处理后的数据:",data_flf.count(axis=0))


#特征编码
label_encoders = {}
categorical_features = ['mainroad', 'guestroom','basement', 'hotwaterheating', 'airconditioning', 'prefarea', 'furnishingstatus']
for feature in categorical_features:
    label_encoders[feature] = LabelEncoder()
    data_flf[feature] = label_encoders[feature].fit_transform(data_flf[feature])



from sklearn.model_selection import train_test_split
x=data_flf.drop('price',axis=1)
y=data_flf['price']
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)


# 模型选择和训练
# from sklearn.ensemble import RandomForestRegressor
# model = RandomForestRegressor(n_estimators=100, random_state=42)
# model.fit(x_train,y_train)

from sklearn.linear_model import LinearRegression
model=LinearRegression()
model.fit(x_train,y_train)

result=model.score(x_test,y_test)
print("准确率:",result)


# 新房屋的数据
new_house = {
    'area': 7420,
    'bedrooms': 4,
    'bathrooms': 2,
    'stories': 3,
    'mainroad': label_encoders['mainroad'].transform(['yes'])[0],
    'guestroom': label_encoders['guestroom'].transform(['no'])[0],
    'basement': label_encoders['basement'].transform(['no'])[0],
    'hotwaterheating': label_encoders['hotwaterheating'].transform(['no'])[0],
    'airconditioning': label_encoders['airconditioning'].transform(['yes'])[0],
    'parking': 2,
    'prefarea': label_encoders['prefarea'].transform(['yes'])[0],
    'furnishingstatus': label_encoders['furnishingstatus'].transform(['furnished'])[0]
}

# 将新房屋数据转换为DataFrame
new_house_df = pd.DataFrame([new_house])

# 预测新房屋的价格
predicted_price = model.predict(new_house_df)
print(f'推测的房价: {predicted_price[0]}')


